<template>
    <div class="user">
        <Breadcrumb name1="用户管理" name2="用户列表"></Breadcrumb>
        <el-card>
            <div class="search">
                <el-input placeholder="请输入内容" v-model="searchKeyword" clearable @clear="search">
                    <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                </el-input>
                <el-button type="primary" @click="addUserDialog = true">添加用户</el-button>
            </div>
            <div>
                <el-table :data="userlist" border stripe>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column prop="username" label="姓名"></el-table-column>
                    <el-table-column prop="email" label="邮箱"></el-table-column>
                    <el-table-column prop="mobile" label="电话"></el-table-column>
                    <el-table-column prop="role_name" label="角色"></el-table-column>
                    <el-table-column label="状态">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row.id,scope.row.mg_state)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200px">
                        <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateDialog(scope.row.id)"></el-button>
                            <el-button type="danger"  icon="el-icon-delete" size="mini" @click="deleteUserDialog(scope.row.id)"></el-button>
                            <el-tooltip effect="dark" content="分配角色" placement="top">
                                <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoleDialogbtn(scope.row)"></el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <pagination 
                    @handleSizeChange="handleSizeChange" 
                    @handleCurrentChange="handleCurrentChange"
                    :totalRecords="total">
                </pagination>
            </div>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addUserDialog"
            width="50%"
            @close="addUserDialogClosed"
            append-to-body>
            <el-form :model="addUserForm" :rules="addUserFormRules" 
            ref="addUserFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部按钮区 -->
            <span slot="footer">
                <el-button @click="addUserDialog = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改用户对话框 -->
        <el-dialog
            title="修改用户"
            :visible.sync="updateUserDialog"
            width="50%"
            @close="updateUserDialogClosed"
            append-to-body>
            <el-form :model="updateUserForm" :rules="updateUserFormRules" 
            ref="updateUserFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="updateUserForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="updateUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="updateUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="updateUserDialog = false">取 消</el-button>
                <el-button type="primary" @click="updateUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配角色对话框 -->
        <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialog"
        width="50%"
        @close="setRoleDialogClose"
        append-to-body>
            <el-form>
                <el-form-item label="当前用户：">{{userIdInfo.username}}</el-form-item>
                <el-form-item label="当前角色：">{{userIdInfo.role_name}}</el-form-item>
                <el-form-item>分配新角色：
                    <el-select v-model="setRoleInfo.rid" placeholder="请选择">
                        <el-option v-for="item in roleList" :key="item.id"
                        :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="setRoleDialog = false">取 消</el-button>
                <el-button type="primary" @click="setRole">确 定</el-button>
            </span>
      </el-dialog>
    </div>
</template>

<script>
import { request } from '../../../api/axios'
import { checkMobile,checkEmail } from "../../../api/check"
import Breadcrumb from "../components/Breadcrumb.vue"
// import pagination from "../components/pagination.vue"
export default {
    name:"Users",
    components:{ Breadcrumb },
    data(){
        return{
            // 查询用户信息渲染的参数
            userInfo:{
                query: '',
                pagenum: 1,     //第几页
                pagesize: 5,     //一页几条数据
            },
            userlist:[],
            total: 0,

            // 搜索框输入关键词
            searchKeyword:"",

            // 添加用户对话框的显示与隐藏
            addUserDialog:false,
            // 添加用户的表单数据
            addUserForm:{
                username:"",
                password: "",
                email: "",
                mobile: "",
            },
            addUserFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '用户名长度3-10位', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 10, message: '密码长度6-15位', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            },

            // 修改用户对话框的显示与隐藏
            updateUserDialog:false,
            // 根据id请求来的修改用户的表单数据
            updateUserForm:{
                // id:"",
                // email: "",
                // mobile: "",
            },
            // 发送修改用户的请求参数
            updateUserInfo:{
                email: "",
                mobile: "",
            },
            // 修改表单的验证规则
            updateUserFormRules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            },

            // 删除用户的id
            deleteUserId:"",

            // 分配角色对话框显示与隐藏
            setRoleDialog:false,
            // 此要修改的用户信息
            userIdInfo:{},
            // 请求来的角色下拉选择列表数据
            roleList:{},
            setRoleInfo:{
                rid:""
            }
        }
    },
    created(){
        this.getUserList()
    },
    methods:{
        // 请求来用户数据列表
        getUserList(){
            request("get","users",this.userInfo)
            .then(res =>{
                console.log(res)
                this.userlist = res.data.users
                this.total = res.data.total
            })
        },

        // 搜索查询
        search(){
            this.userInfo.query=this.searchKeyword
            this.getUserList()
        },

        // 点击按钮，添加新用户
        addUser(){
            this.$refs.addUserFormRef.validate(valid =>{
                if(!valid) return
                request("post","users",this.addUserForm)
                .then(res =>{
                    console.log(res)
                    if(res.meta.status==201){
                        this.$message.success('添加用户成功')
                        this.addUserDialog=false
                        this.getUserList()
                    }
                    else{
                        this.$message.error('添加用户失败')
                    }
                })
            })
        },
        // 关闭添加用户对话框
        addUserDialogClosed() {
            this.$refs.addUserFormRef.resetFields()
        },

        // 修改用户状态
        changeUserState(id,mg_state){
            console.log(id,mg_state)
            request("put","users/"+id+"/state/"+mg_state)
            .then(res =>{
                console.log(res)
                if(res.meta.status==200){
                    this.$message.success('更新状态成功')
                }else{this.$message.error('更新用户状态失败')}
            })
        },

        // 点击修改用户按钮打开修改用户对话框
        updateDialog(id){
            this.updateUserDialog=true
            request("get","users/"+id)
            .then(res =>{
                console.log(res)
                this.updateUserForm=res.data
            })
        },
        // 关闭修改用户对话框
        updateUserDialogClosed() {
            this.$refs.updateUserFormRef.resetFields()
        },
        // 修改用户
        updateUser(){
            this.updateUserInfo.email=this.updateUserForm.email
            this.updateUserInfo.mobile=this.updateUserForm.mobile
            this.$refs.updateUserFormRef.validate(valid =>{
                if(!valid) return
                request("put","users/"+this.updateUserForm.id,this.updateUserInfo)
                .then(res =>{
                    console.log(res)
                    if(res.meta.status==200){
                        this.$message.success('更新用户信息成功')
                        this.updateUserDialog=false
                        this.getUserList()
                    }else{this.$message.error('更新用户信息失败')}
                })
            })
        },

        // 删除用户对话框
        deleteUserDialog(id){
            this.$confirm('您确定要删除该数据吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(()=>{
                this.deleteUserId=id
                this.deleteUser()
            })
        },
        deleteUser(){
            request("delete","users/"+this.deleteUserId)
            // this.$http.delete("users/"+this.deleteUserId)
            .then(res=>{
                console.log(res)
                if(res.meta.status==200){
                    this.$message.success('删除用户成功')
                    this.getUserList()
                }else{this.$message.error('删除用户失败')}
            })
            .catch(err =>{
                console.log(err)
            })
        },

        // 点击分配角色，传入该用户信息
        setRoleDialogbtn(info){
            this.setRoleDialog=true
            this.userIdInfo=info
            // 请求来所有角色
            request("get","roles").then(res =>{     //1.5.1
                console.log(res)
                this.roleList = res.data
            })
        },
        // 分配角色
        setRole(){
            if(this.setRoleInfo.rid==""){
                this.$message.error('请选择要分配的角色')
            }
            else{
                request("put","users/"+this.userIdInfo.id+"/role",this.setRoleInfo)     //1.3.7
                .then(res=>{
                    console.log(res)
                    if(res.meta.status==200){
                        this.$message.success('更新角色成功')
                        this.setRoleDialog=false
                        this.getUserList()
                    }
                })
            }
            
        },
        // 关闭分配角色对话框，清空选项下拉框内容
        setRoleDialogClose(){
            this.setRoleInfo.rid=""
        },

        // 分页
        handleSizeChange(val) {
            this.userInfo.pagesize = val
            this.getUserList();
            // this.handleCurrentChange(1)
        },
        //第几页
        handleCurrentChange(val) {
            this.userInfo.pagenum = val
            this.getUserList();
        },
    }
}
</script>

<style scoped>
.search .el-input{
    width: 40%;
    margin-right: 20px;
}
.el-table{
    margin-top: 15px;
}
</style>